package com.training.controller;

import com.training.entity.User; // 导入 User 实体
import com.training.entity.Teacher; // 导入 Teacher 实体
import com.training.service.TeacherService; // 导入 TeacherService

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession; // 导入 HttpSession

@Controller
@RequestMapping("/teacher") // 确保这个类级别的注解存在且路径正确
public class TeacherController {

    private final TeacherService teacherService; // 注入 TeacherService

    @Autowired
    public TeacherController(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    @GetMapping("/dashboard")
    public String showTeacherDashboard(Model model, HttpSession session) { // 添加 HttpSession 参数
        System.out.println("成功进入 TeacherController 的 showTeacherDashboard 方法");

        // 1. 从 Session 获取登录用户对象
        User loggedInUser = (User) session.getAttribute("loggedInUser");

        // 2. 检查用户是否已登录，以及角色是否为 TEACHER
        if (loggedInUser == null || !"TEACHER".equalsIgnoreCase(loggedInUser.getRole())) {
            // 如果未登录或角色不正确，重定向到登录页面
            // 可以在这里添加错误消息到 redirectAttributes
            return "redirect:/login";
        }

        // 3. 将 loggedInUser 添加到 Model 中，供 Thymeleaf 访问
        model.addAttribute("loggedInUser", loggedInUser);
        System.out.println("将 loggedInUser 添加到 Model，用户名为: " + loggedInUser.getUsername());

        // 4. 获取教师信息并添加到 Model (这是你之前已经有的逻辑)
        Teacher teacher = teacherService.getTeacherByUserId(loggedInUser.getId());
        model.addAttribute("teacher", teacher);
        if (teacher != null) {
            System.out.println("找到教师信息，教师姓名: " + teacher.getTeaName());
        } else {
            System.out.println("未找到与用户ID " + loggedInUser.getId() + " 关联的教师信息。");
        }


        // 确保你的模板文件名为 teacher-dashboard.html 并且在 templates 目录下
        return "teacher-dashboard";
    }
}